<?php


namespace app\common\controller;


use think\Controller;
use think\Db;
use think\Exception;
use think\Session;

class Upload extends Controller
{
    //图片列表视图
    public function index(){
        $newyear = date('Y');
        $year = [];
        for ($i=0;$i<3;$i++){
            $year[] = $newyear-$i;
        }
        $month = [1,2,3,4,5,6,7,8,9,10,11,12];
        //查询分组

        $table = Session::get("table");
        $role = Session::get("role");
        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];
        if($table!="account"){
            $where['table'] = $table;
            $where['add_id'] = Session::get("id");
        }

        $group = Db::name("upload_group")->where($where)->select();
        $this->assign('group',$group);
        $this->assign('month',$month);
        $this->assign('year',$year);

        $type = empty($_POST['multiple'])?"upload":$_POST['multiple'];
        $this->assign('type',$type);

        $newkey = empty($_POST['newkey'])?"":$_POST['newkey'];
        $this->assign('newkey',$newkey);
        return view("index");
    }

    public function ajaxlist(){
        $pageSize = 9;
        $page = empty($_GET['curPage'])?1:$_GET['curPage'];
        $start = ($page-1)*$pageSize;
        $where = [];
        if(!empty($_GET['group_id'])){
            $where['group_id'] = $_GET['group_id'];
        }

        if(!empty($_GET['year'])){
            $where['insertdata'] = ['like','%'.$_GET['year'].'%'];
        }
        if(!empty($_GET['month'])){
            $where['insertdata'] = ['like','%'.$_GET['month'].'%'];
        }

        if(!empty($_GET['year']) && !empty($_GET['month'])){

            $month = ($_GET['month']<10)?'0'.$_GET['month']:$_GET['month'];
            $where['insertdata'] = ['like','%'.$_GET['year']."-".$month.'%'];
        }

        $table = Session::get("table");
        $thisWechat = Session::get("thisWechat");
        $where['uniacid'] = $thisWechat['id'];
        if($table!="account"){
            $where['table'] = $table;
            $where['add_id'] = Session::get("id");
        }
        $where['type'] = 3;

        $list = Db::name("upload_images")->where($where)->limit($start,$pageSize)->order("id desc")->select();
        $totalItem = Db::name("upload_images")->where($where)->count("id");
        $totalPage = ceil($totalItem/$pageSize);
        $black['code'] = 0;
        $black['totalItem'] = $totalItem;
        $black['totalItem'] = $pageSize;
        $black['page'] = $page;
        $black['totalPage'] = $totalPage;
        $black['data_content'] = $list;
        return $black;
    }


    //删除分组
    public function delGroup(){
        if($_POST){
            $data['id'] = $_POST['id'];
            $return = Db::name("upload_group")->delete($data);
        }
        if(empty($return)){
            $black['code'] = 202;
            $black['msg'] = "操作失败";
        }else{
            $black['code'] = 0;
            $black['msg'] = "操作成功";
            $black['id'] = $return;
        }
        return $black;
    }

    //添加分组
    public function addGroup(){
        $thisWechat = Session::get("thisWechat");
        if($_POST){
            $data['name'] = $_POST['name'];
            $data['uniacid'] = $thisWechat['id'];
            if(empty($_POST['id'])){
                $data['table'] = Session::get("table");
                $data['addtime'] = time();
                $data['add_id'] = Session::get("id");
                $return = Db::name("upload_group")->insertGetId($data);
            }else{
                $id = $_POST['id'];
                unset($data['id']);
                $data['update_table'] = Session::get("table");
                $data['updatetime'] = time();
                $data['update_id'] = Session::get("id");
                $return = Db::name("upload_group")->where(['id'=>$id])->update($data);
            }
        }

        if(empty($return)){
            $black['code'] = 202;
            $black['msg'] = "操作失败";
        }else{
            $black['code'] = 0;
            $black['msg'] = "操作成功";
            $black['id'] = $return;
        }
        return $black;
    }

    /**
     * 图片上传
     */
    public function upload()
    {
        try{
            $thisWechat = Session::get("thisWechat");
            // 获取表单上传文件
            $file = request()->file('filesToUpload');

            foreach ($file as $k=>$v){

                $newdata = $v->getInfo();
                $type = $this->file_format($newdata['name']);
                if($type==6){
                    throw new Exception("上传文件格式有误");
                }
//                if($type<=3){
//                    if($newdata['size']>1024000){
//                        throw new Exception("图片大小超过限制，请上传1M以内的图片");
//                    }
//                }
                $ContentType = $newdata['type'];

                $info = $v->move(ROOT_PATH.'public'.DS.'upload');
                $filename = DS.'upload'.DS.$info->getSaveName();

//                $img = imagecreatefrompng(ROOT_PATH . 'public' . $filename);
//                $width = imagesx($img);


                //图片压缩
                $this->compressedImage(ROOT_PATH . 'public' . $filename,ROOT_PATH . 'public' . $filename);

                $group_id = $data['group_id'] = empty($_GET['group_id'])?-1:$_GET['group_id'];
                $real_path = $info->getRealPath();
                $size = 0;
                if(file_exists($real_path)){
                    clearstatcache();
                    $size = filesize($real_path);
                }
                //保存值腾讯云
                $src = $this->putObject(ROOT_PATH . 'public' . $filename,$group_id,$size,$type,$ContentType);
                if(file_exists($real_path)){
                    unset($info);
                    unlink($real_path);  //删除文件
                }
            }
            $black['code'] = 0;
            $black['msg'] = "上传成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;

    }

    //删除图片
    public function delImages(){
        $images = $_POST['images'];
        $images = explode(";",$images);
        try{
            foreach ($images as $k=>$v){
                $v = explode(":",$v);
                if(!empty($v)){
                    $this->deleteObject($v[0]);
                }
            }
            $black['code'] = 0;
            $black['msg'] = "删除成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;
    }

    //腾讯云账号信息
    public function objectConfig(){
        require ROOT_PATH."extend/cos/vendor/autoload.php";//引入PHPExcel加载文件
        $secretId = "AKIDDAqOnvZfYeZDbrjYzFMD4ezhhXiYKUYK"; //"云 API 密钥 SecretId";
        $secretKey = "zi9JM6jG6gz3vb3E9tR4RbW9bnCOKzRf"; //"云 API 密钥 SecretKey";
        $region = "ap-nanjing"; //设置一个默认的存储桶地域

        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => $region,
                'schema' => 'http', //协议头部，默认为http
                'credentials'=> array(
                    'secretId'  => $secretId ,
                    'secretKey' => $secretKey)));
        return $cosClient;
    }

    //腾讯云删除
    public function deleteObject($id){
        $thisWechat = Session::get("thisWechat");
        $cosClient = $this->objectConfig();
        $detail = Db::name("upload_images")->where(['id'=>$id])->find();
        try {
            $key = 'platform'.$detail['uniacid'].'/'.$detail['insertdata'].'/'.$detail['name'];
            $result = $cosClient->deleteObject(array(
                'Bucket' => 'tickets-1253901423', //格式：BucketName-APPID
                'Key' => $key,
            ));
            Db::name("upload_images")->where(['id'=>$id])->delete();
        } catch (\Exception $e) {
            // 请求失败
            echo($e);
        }
    }




    //处理文件流
    public function uploads(){
        //$logo_data = $this->request->post('logo_base64','');
        $logo_data = $_POST['content'];

        if(!empty($logo_data)){
            //$data = file_get_contents('./1.txt');
            $reg = '/data:image\/(\w+?);base64,(.+)$/si';
            preg_match($reg,$logo_data,$match_result);
            $file_name = time().'.'.$match_result[1];
            $logo_path = ROOT_PATH . 'public' . DS . 'upload/'.date("Ym").DS;
            if(!is_dir($logo_path))
            {
                is_file($logo_path) or mkdir($logo_path,0700);
            }
            $logo_path .=$file_name;
            $num = file_put_contents($logo_path,base64_decode($match_result[2]));
            if(!empty($num)){
                //上传成功之后，再进行缩放操作
                //$image = \think\Image::open($logo_path);
                // 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
                //$image->thumb(102, 36)->save($logo_path);
                $black['code'] = 0;
                $black['msg'] = "上传成功";
                $black['path'] = '/upload/'.date("Ym").DS.$file_name;
            }else{
                $black['code'] = 202;
                $black['msg'] = "上传失败";
            }
        }else{
            $black['code'] = 202;
            $black['msg'] = "请上传图片";
        }
        return $black;
    }

    /**
     * 图片格式转换
     * @param string $image_path 文件路径或url
     * @param string $to_ext 待转格式，支持png,gif,jpeg,wbmp,webp,xbm
     * @param null|string $save_path 存储路径，null则返回二进制内容，string则返回true|false
     * @return boolean|string $save_path是null则返回二进制内容，是string则返回true|false
     * @throws Exception
     * @author klinson <klinson@163.com>
     */
    function transform_image($image_path, $to_ext = 'jpeg')
    {
        if (! in_array($to_ext, ['png', 'gif', 'jpeg', 'wbmp', 'webp', 'xbm','jpg'])) {
            throw new Exception('unsupport transform image to ' . $to_ext);
        }

        //$image_path = ROOT_PATH . 'public' . DS . 'upload/'.date("Ym").DS.$image_path;
        $image_path = ROOT_PATH . 'public' . DS . $image_path;
        switch (exif_imagetype($image_path)) {
            case IMAGETYPE_GIF :
                $img = imagecreatefromgif($image_path);
                break;
            case IMAGETYPE_JPEG :
            case IMAGETYPE_JPEG2000:
                $img = imagecreatefromjpeg($image_path);
                break;
            case IMAGETYPE_PNG:
                $img = imagecreatefrompng($image_path);
                break;
            case IMAGETYPE_BMP:
            case IMAGETYPE_WBMP:
                $img = imagecreatefromwbmp($image_path);
                break;
            case IMAGETYPE_XBM:
                $img = imagecreatefromxbm($image_path);
                break;
            case IMAGETYPE_WEBP: //(从 PHP 7.1.0 开始支持)
                $img = imagecreatefromwebp($image_path);
                break;
            default :
                throw new \Exception('Invalid image type');
        }
        $function = 'image'.$to_ext;
        $imgname = uniqid().'.'.$to_ext;
        $tmp = ROOT_PATH . 'public' . DS . 'upload/'.date("Ym").'/'.$imgname;
        if ($function($img, $tmp)) {
            $content = file_get_contents($tmp);
            unlink($image_path); //删除原始图片
            return $imgname;
        } else {
            unlink($tmp);
            throw new \Exception('the file '.$tmp.' can not write');
        }
    }


    //多图片上传
    public function newupload()
    {
        $typeArr = array("jpg", "png", "gif", "ico");
        $thisWechat = Session::get("thisWechat");
//允许上传文件格式
        $path = ROOT_PATH . 'public' . DS . 'upload/'."platform".$thisWechat['id'].DS.date("Ym").DS;
        if(!is_dir($path))
        {
            is_file($path) or mkdir($path,0700);
        }
//上传路径
//if (!file_exists($path)) {
//	mkdir($path);
//}
        if (isset($_POST)) {
            $name = $_FILES['file']['name'];
            $size = $_FILES['file']['size'];
            $name_tmp = $_FILES['file']['tmp_name'];
            if (empty($name)) {
                echo json_encode(array("error" => "您还未选择图片"));
                exit;
            }
            $type = strtolower(substr(strrchr($name, '.'), 1));
            //获取文件类型

            if (!in_array($type, $typeArr)) {
                echo json_encode(array("error" => "清上传jpg,png或gif类型的图片！"));
                exit;
            }
            if ($size > (500 * 1024)) {
                echo json_encode(array("error" => "图片大小已超过500KB！"));
                exit;
            }

            $pic_name = time() . rand(10000, 99999) . "." . $type;
            //图片名称
            $pic_url = $path . $pic_name;
            //上传后图片路径+名称
            if (move_uploaded_file($name_tmp, $pic_url)) {//临时文件转移到目标文件夹
                $pic = '/upload/'."platform".$thisWechat['id'].DS.date("Ym").DS.$pic_name;
                echo json_encode(array("error" => "0", "pic" => $pic, "name" => $pic_name));
            } else {
                echo json_encode(array("error" => "上传有误，清检查服务器配置！"));
            }

        }
    }


    /**
     * 图片上传(富文本编辑器)
     */
    public function textUpload()
    {
        try{
            // 获取表单上传文件
            $file = request()->file('file');
            if (empty($file)) {
                throw new Exception("请选择上传文件");
            }

            $type = $this->file_format($_FILES['file']['name']);
            if($type==6){
                throw new Exception("上传文件格式有误");
            }
            if($type<=3){
                if($_FILES['file']['size']>1024000){
                    throw new Exception("图片大小超过限制，请上传1M以内的图片");
                }
            }

            $ContentType = $_FILES['file']['type'];

            $thisWechat = Session::get("thisWechat");
            // 移动到框架应用根目录/public/uploads/ 目录下
            $path = ROOT_PATH . 'public' . DS . 'upload'.DS."platform".$thisWechat['id'];
            $info = $file->move($path);
            $filename = DS . 'upload' .DS."platform".$thisWechat['id']. DS . $info->getSaveName();  //在测试的时候也可以直接打印文件名称来查看
            if($type<=3){
                //图片压缩
                $this->compressedImage(ROOT_PATH . 'public' . $filename,ROOT_PATH . 'public' . $filename);
            }

            $real_path = $info->getRealPath();
            $size = 0;
            if(file_exists($real_path)){
                clearstatcache();
                $size = filesize($real_path);
            }

            //保存值腾讯云
            $src = $this->putObject(ROOT_PATH . 'public' . $filename,-2,$size,$type,$ContentType);

            if ($src) {
                if(file_exists($real_path)){
                    unset($info);
                    unlink($real_path);  //删除文件
                }
                $black['code'] = 0;
                $black['msg'] = "上传成功";
                $black['data']['src'] = $src;
                $black['path'] = $src;
            }else{
                throw new Exception("上传失败");
            }
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return json_encode($black);

    }


    /**
     * desription 压缩图片
     * @param sting $imgsrc 图片路径
     * @param string $imgdst 压缩后保存路径
     */
    public function compressedImage($imgsrc, $imgdst) {
        list($width, $height, $type) = getimagesize($imgsrc);

        $new_width = $width;//压缩后的图片宽
        $new_height = $height;//压缩后的图片高

        if($width >= 1200){
            $per = 1200 / $width;//计算比例
            $new_width = $width * $per;
            $new_height = $height * $per;
        }
        switch ($type) {
            case 1:
                $giftype = check_gifcartoon($imgsrc);
                if ($giftype) {
                    header('Content-Type:image/gif');
                    $image_wp = imagecreatetruecolor($new_width, $new_height);
                    $image = imagecreatefromgif($imgsrc);
                    imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                    //90代表的是质量、压缩图片容量大小
                    imagejpeg($image_wp, $imgdst, 75);
                    imagedestroy($image_wp);
                    imagedestroy($image);
                }
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image_wp = imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefromjpeg($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                //90代表的是质量、压缩图片容量大小
                imagejpeg($image_wp, $imgdst, 75);
                imagedestroy($image_wp);
                imagedestroy($image);
                break;
            /*case 3:
                header('Content-Type:image/png');
                $image_wp = imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefrompng($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                //90代表的是质量、压缩图片容量大小
                imagejpeg($image_wp, $imgdst, 75);
                imagedestroy($image_wp);
                imagedestroy($image);
                break;*/
        }
    }



    //腾讯云上传
    public function putObject($local_path,$group_id=0,$size=0,$type=0,$ContentType='image/jpeg'){
        $thisWechat = Session::get("thisWechat");
        $cosClient = $this->objectConfig();
        try {
            $platform = "platform".$thisWechat['id']; //平台
            $time = date("Y-m-d"); //日期
            $name = md5(microtime()).".".substr(strrchr($local_path, '.'), 1); //文件名
            $result = $cosClient->putObject(array(
                'Bucket' => 'tickets-1253901423', //格式：BucketName-APPID
                'Key' =>$platform.'/' .$time.'/'.$name,
                'Body' => fopen($local_path, 'rb'),
                "ContentType" => $ContentType
            ));
            // 请求成功
            $array = (array)$result;
            foreach ($array as $key => $value) {
                $src = "https://".$value['Location'];
                $ETag = $value['ETag'];
            }
            //保存图片信息到数据库
            $data['group_id'] = $group_id;
            $data['path'] = $src;
            $data['ETag'] = $ETag;
            $data['name'] = $name;
            $data['size'] = $size;
            $data['insertdata'] = date("Y-m-d");
            $data['add_id'] = Session::get("id");
            $data['addtime'] = time();
            $data['table'] = Session::get("table");
            $data['uniacid'] = $thisWechat['id'];
            $data['type'] = $type;
            $data['ContentType'] = $ContentType;
            Db::name("upload_images")->insert($data);
            return $src;
            /*$black['code'] = 0;
            $black['msg'] = "上传成功";
            $black['data']['src'] = "https://".$src;*/
        } catch (\Exception $e) {
            echo $e->getMessage();
            // 请求失败
            throw new Exception("上传有误");
        }
    }


    function file_format($file)
    {
        // 取文件后缀名
        $str = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        //strtolower 将所有字符转换为小写
        //pathinfo 获取文件信息，详细用法见下面我的补充
        // 文档格式
        $text = array('doc','docx','ppt','xls','xlsx','wps','txt','pdf','word');
        // 压缩格式
        $zip = array('rar', 'zip', 'tar',  'jar',  '7-zip', 'arj', 'gzip','tz');
        // 图片格式
        $image = array('jpg', 'png', 'ico', 'bmp', 'gif', 'tif',  'bmp',  'jpeg', 'svg');
        $video = array('mp4');
        //音频格式
        $audio = array('mp3');
        // 匹配不同的结果
        if (in_array($str, $text)) {
            return 1;
        } elseif (in_array($str, $zip)) {
            return 2;
        } elseif (in_array($str, $image)) {
            return 3;
        } elseif (in_array($str, $video)) {
            return 4;
        } elseif (in_array($str, $audio)) {
            return 5;
        } else {
            return 6;
        }
    }

    /**
     * 图片上传(不存储数据库)
     */
    public function ad_upload()
    {
        // 获取表单上传文件
        $file = request()->file('file');
        $thisWechat = Session::get("thisWechat");
        $info = $file->move(ROOT_PATH.'public'.DS.'upload'.DS."platform".$thisWechat['id']);

        //获取文件（文件名），$info->getFilename()  ***********存储的文件名
        //获取文件（日期/文件名），$info->getSaveName()  **********文件地址
        //$info->getInfo()['name'] 原始文件名称

        $imageType = $info->getExtension();
        $image = $info->getSaveName(); //输出的为uploads后面的路径,可以打印查看
        /*if ($imageType == 'jpg') {
            // 获取完整路径
            $image = ROOT_PATH.'/public'.DS.'upload'.DS.$info->getSaveName();
            // 加载图片资源
            $src = @imagecreatefromjpeg($image);
            list($width, $height) = getimagesize($image); //获取图片的高度
            $newwidth = $width;   //宽高可以设置, 楼主是想让它的宽高不变才没赋值
            $newheight = $height;
            $tmp = imagecreatetruecolor($newwidth, $newheight); //生成新的宽高
            imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); //缩放图像
            $output = imagejpeg($tmp, $image, 50); //第三个参数(0~100);越大越清晰,图片大小也高;   png格式的为(1~9)
            imagedestroy($tmp); // 销毁原来图片,一般不使用
            // 请参考jpg中的详解
        } elseif ($imageType == 'png') {
            // 获取完整路径
            $image = ROOT_PATH.'/public'.DS.'upload'.DS.$info->getSaveName();
            $src = @imagecreatefrompng($image);
            list($width, $height) = getimagesize($image);
            $newwidth = $width;
            $newheight = $height;
            $tmp = imagecreatetruecolor($newwidth, $newheight);
            imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
            $output = imagepng($tmp, $image, 5);  //这个图片的第三参数(1~9)
            imagedestroy($tmp);
        }*/
        $filename = DS.'upload'.DS."platform".$thisWechat['id'].DS.$info->getSaveName();
        if(empty($_GET['group_id']) || $_GET['group_id']<=0){
            $_GET['group_id'] = 0;
        }

        if(!$filename){
            $this->error($file->getError());
        }
        $black['code'] = 0;
        $black['msg'] = "上传成功";
        $black['path'] = $filename;
        return $black;
    }


    /**
     * 图片上传(不存储数据库)
     */
    public function js_upload()
    {
        // 获取表单上传文件
        $file = request()->file('file');

        $thisWechat = Session::get("thisWechat");


        $path = ROOT_PATH.'public'.DS.'upload'.DS."platform".$thisWechat['id'];

        $info = $file->move($path);

        //获取文件（文件名），$info->getFilename()  ***********存储的文件名
        //获取文件（日期/文件名），$info->getSaveName()  **********文件地址
        //$info->getInfo()['name'] 原始文件名称

        /*$imageType = $info->getExtension();
        $image = $info->getSaveName(); //输出的为uploads后面的路径,可以打印查看
        if ($imageType == 'jpg') {
            // 获取完整路径
            $image = ROOT_PATH.'/public'.DS.'upload'.DS.$info->getSaveName();

            // 加载图片资源
            $src = @imagecreatefromjpeg($image);
            list($width, $height) = getimagesize($image); //获取图片的高度
            $newwidth = $width;   //宽高可以设置, 楼主是想让它的宽高不变才没赋值
            $newheight = $height;
            $tmp = imagecreatetruecolor($newwidth, $newheight); //生成新的宽高
            imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); //缩放图像
            $output = imagejpeg($tmp, $image, 50); //第三个参数(0~100);越大越清晰,图片大小也高;   png格式的为(1~9)
            imagedestroy($tmp); // 销毁原来图片,一般不使用
            // 请参考jpg中的详解
        } elseif ($imageType == 'png') {
            // 获取完整路径
            $image = ROOT_PATH.'/public'.DS.'upload'.DS.$info->getSaveName();
            $src = @imagecreatefrompng($image);
            list($width, $height) = getimagesize($image);
            $newwidth = $width;
            $newheight = $height;
            $tmp = imagecreatetruecolor($newwidth, $newheight);
            imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
            $output = imagepng($tmp, $image, 5);  //这个图片的第三参数(1~9)
            imagedestroy($tmp);
        }*/


        //人脸识别
        $filename = DS.'upload'.DS."platform".$thisWechat['id'].DS.$info->getSaveName();
        /*$images = "https://".$_SERVER['HTTP_HOST'].$filename;
        //调用百度Api
        $res = $this->baiApi();

        unset($info);*/
        /*if(empty($res['access_token'])){
            $image_path = ROOT_PATH . 'public' . DS . $filename;
            unlink($image_path);
            $black['code'] = 202;
            $black['msg'] = "上传失败";
            return $black;
        }
        //检测人脸
        $bodys['image'] = $images;
        $bodys['image_type'] = "URL";
        $bodys['face_field'] = "faceshape,facetype";
        $bodys = json_encode($bodys);
        $fance = $this->fance($res['access_token'],$bodys);

        if(!empty($fance['error_code'])){
            $image_path = ROOT_PATH . 'public' . DS . $filename;
            unlink($image_path);
            $black['code'] = 202;
            $black['msg'] = "请上传人脸头像";
            return $black;
        }*/
        //人脸识别end
        //$filename = $this->transform_image($filename);
        //$filename = '/upload/'.date("Ym").'/'.$filename;

        $filename = $filename;

        if(empty($_GET['group_id']) || $_GET['group_id']<=0){
            $_GET['group_id'] = 0;
        }

        if(!$filename){
            $this->error($file->getError());
        }
        $black['code'] = 0;
        $black['msg'] = "上传成功";
        $black['path'] = $filename;
        return $black;
    }


    public function request_post($url = '', $param = '') {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($curl);//运行curl
        curl_close($curl);
        return $data;
    }

    //调用人脸识别
    public function fance($access_token,$bodys){
        $token =$access_token;
        $url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=' . $token;
        $res = $this->request_post($url, $bodys);
        $res = json_decode($res,true);
        return $res;
    }


    public function baiApi(){
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        //$url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type']       = 'client_credentials';
        $post_data['client_id']      = '7sRu0qPIE2Qf2SPuDDPeUhm9';
        $post_data['client_secret'] = 'UnDW0ipU7UjDh7eznGq7Yy1XFH6wd9af';
        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $res = $this->request_post($url, $post_data);
        $res = json_decode($res,true);
        return $res;
    }
    /*function file_format($file)
    {
        // 取文件后缀名
        $str = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        //strtolower 将所有字符转换为小写
        //pathinfo 获取文件信息，详细用法见下面我的补充
        // 文档格式
        $text = array('doc', 'docx', 'ppt', 'xls', 'xlsx', 'wps', 'txt', 'lrc', 'wfs', 'torrent', 'html', 'htm', 'java', 'js', 'css', 'less', 'php', 'pdf', 'pps', 'host', 'box', 'word', 'perfect', 'dot', 'dsf', 'efe', 'ini', 'json', 'lnk', 'log', 'msi', 'ost', 'pcs', 'tmp', 'xlsb');
        // 压缩格式
        $zip = array('rar', 'zip', 'tar', 'cab', 'uue', 'jar', 'iso', 'z', '7-zip', 'ace', 'lzh', 'arj', 'gzip', 'bz2', 'tz');
        // 图片格式
        $image = array('webp', 'jpg', 'png', 'ico', 'bmp', 'gif', 'tif', 'pcx', 'tga', 'bmp', 'pxc', 'tiff', 'jpeg', 'exif', 'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps', 'ai', 'hdri');
        $video = array('mp4', 'avi', '3gp', 'rmvb', 'gif', 'wmv', 'mkv', 'mpg', 'vob', 'mov', 'flv', 'swf', 'ape', 'm4a', 'm4r', 'ogg', 'wavpack');
        //音频格式
        $audio = array('wav', 'aif', 'au', 'mp3', 'ram', 'wma', 'mmf', 'amr', 'aac', 'flac');
        // 匹配不同的结果
        if (in_array($str, $text)) {
            return 1;
        } elseif (in_array($str, $zip)) {
            return 2;
        } elseif (in_array($str, $image)) {
            return 3;
        } elseif (in_array($str, $video)) {
            return 4;
        } elseif (in_array($str, $audio)) {
            return 5;
        } else {
            return 6;
        }
    }*/


}